import { Breadcrumb, Button, Col, Space, Table, TableProps, Row, Modal, message } from 'antd';
import React from 'react';
import {
  FormPanel,
  type FormPanelType,
  InputType,
  FormPanelBtnAlign,
  FormPanelObject,
  StandUploadExcel,
  Utils,
} from 'lfun-bg-comp';
import { useNavigate } from 'react-router-dom';
import { useLocation } from 'react-router';
import _ from 'lodash';
import dayjs from 'dayjs';
import { PageContainer } from '@/component/page-container';
import { KG_ORDER_STATUS } from '@/constant/schoolOptions';
import { PAGINATIONCONFIG } from '@/constant/page';
import styles from './index.less';
import Create from './create';
import {
  CloseInstitution,
  closeInstitution,
  deleteInstitution,
  importInstitution,
  searchInstitution,
  exportStuInfo,
} from '@/service/unit/institution';
import { getInstitutionCategory, get_stoge_pz, set_stoge_pz } from '@/utils';
import CloseReson from '../component/closeReson';
import { IMPORT_EXCEL_TEMPLATE } from '@/constant';
import PermissionButton, { isPermissionOperate } from '@/component/permission-button';
import useCountry from '@/hooks/useCountry';

const Groups: React.FC = () => {
  const location = useLocation();
  const [current, setCurrent] = React.useState();
  const [dataSource, setDataSource] = React.useState([]);
  const [total, setTotal] = React.useState(0);
  const [pageSize, setPageSize] = React.useState(get_stoge_pz());
  const [pageIndex, setPageIndex] = React.useState(1);
  const [form, setForm] = React.useState(null);
  const [showCreate, setShowCreate] = React.useState(false);
  const [tableLoading, setTableLoading] = React.useState(false);
  const [showCloseResone, setShowCloseResone] = React.useState(false);
  const country = useCountry();

  const navigate = useNavigate();
  const buildBtns = () => {
    return [
      <PermissionButton permission="export">
        <Button
          type="primary"
          onClick={async () => {
            const res = await exportStuInfo(form.getFieldsValue());
            if (res.success) {
              message.success('导出操作成功,请耐心等待完成,去任务管理下载!');
              return;
            }
            message.error(`导出操作失败,${res.message || res.detail}`);
          }}
        >
          导出
        </Button>
      </PermissionButton>,
    ];
  };
  const search = async (params, pageSize, pageIndex) => {
    setTableLoading(true);
    const res = await searchInstitution({
      ...params,
      page: pageIndex,
      per_page: pageSize,
      institution_category: getInstitutionCategory(),
    });
    if (res.success) {
      setDataSource(res.data.items);
      setPageIndex(pageIndex);
      setPageSize(pageSize);
      setTotal(res.data.total);
    }
    setTableLoading(false);
  };
  const searchTemplate: FormPanelType[] = [
    {
      title: '',
      labelCol: { span: 8 },
      wrapperCol: { span: 14 },
      inputs: [
        {
          label: '机构编码',
          name: 'institution_code',
          key: 'institution_code',
          textRange: [0, 50],
        },
        {
          label: '单位名称',
          name: 'institution_name',
          key: 'institution_name',
          textRange: [0, 20],
        },
        // {
        //   label: '办别',
        //   name: 'institution_org_type',
        //   key: 'institution_org_type',
        //   inputType: InputType.select,
        //   renderOption: SCHOOL_ORG_TYPE,
        // },
        {
          label: '状态',
          name: 'status',
          key: 'status',
          inputType: InputType.select,
          renderOption: KG_ORDER_STATUS,
        },
        {
          label: '行政管辖区',
          name: 'borough',
          key: 'borough',
          inputType: InputType.select,
          renderOption: country,
        },
        {
          label: '地域管辖区',
          name: 'block',
          key: 'block',
          inputType: InputType.select,
          renderOption: country,
        },
      ],
    },
  ];
  const columns: TableProps['columns'] = [
    {
      title: '行政管辖区',
      dataIndex: 'borough',
      key: 'borough',
      render: (text: any) => {
        return _.find(country, { value: text })?.label;
      },
    },
    {
      title: '地域管辖区',
      dataIndex: 'block',
      key: 'block',
      render: (text: any) => {
        return _.find(country, { value: text })?.label;
      },
    },
    {
      title: '单位名称',
      dataIndex: 'institution_name',
      key: 'institution_name',
    },
    // {
    //   title: '机构类型',
    //   dataIndex: 'institution_category',
    //   key: 'institution_category',
    //   render: (text: string) => {
    //     return selectDictLabel(INSTITUTION_TYPE, text);
    //   },
    // },
    {
      title: '社会信用',
      dataIndex: 'social_credit_code',
      key: 'social_credit_code',
    },
    {
      title: '隶属单位号',
      dataIndex: 'membership_no',
      key: 'membership_no',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (text: any) => {
        return _.find(KG_ORDER_STATUS, { value: text })?.label;
      },
    },
    // {
    //   title: '成立时间',
    //   dataIndex: 'create_date',
    //   key: 'create_date',
    //   render: (text: any) => {
    //     if (text) {
    //       return dayjs(text).format('YYYY-MM-DD');
    //     }
    //     return '';
    //   },
    // },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      //width: 320,
      align: 'center',
      hidden: !isPermissionOperate(),
      render: (text, record) => {
        return (
          <Space size="middle">
            <PermissionButton permission="view">
              <Button
                type="link"
                onClick={() => {
                  navigate(`${location.pathname}/details/${record.id}`);
                }}
              >
                查看
              </Button>
            </PermissionButton>
            {['draft', 'opening'].includes(record.status) && record.workflow_status !== 'needaudit' ? (
              <PermissionButton permission="edit">
                <Button
                  key="edit"
                  type="link"
                  size="small"
                  onClick={() => {
                    navigate(`${location.pathname}/change/${record.id}`, { state: { ...record } });
                  }}
                >
                  编辑
                </Button>
              </PermissionButton>
            ) : (
              ''
            )}
            {record.status === 'draft' && record.workflow_status !== 'needaudit' ? (
              <PermissionButton permission="delete">
                <Button
                  type="link"
                  onClick={() => {
                    Modal.confirm({
                      title: '删除',
                      content: `是否删除师德考核时间: ${record.ethics_assessment_date} 相关信息?`,
                      onOk: async () => {
                        console.log('OK');
                        const res = await deleteInstitution(record.teacher_ethic_records_id);
                        if (res.success) {
                          message.success('删除成功');
                          search(form.getFieldsValue(), pageSize, pageIndex);
                        }
                      },
                    });
                  }}
                >
                  删除
                </Button>
              </PermissionButton>
            ) : (
              ''
            )}
            {['normal'].includes(record.status) && record.workflow_status !== 'needaudit' ? (
              <PermissionButton permission="change">
                <Button
                  type="link"
                  onClick={() => {
                    navigate(`${location.pathname}/change/${record.id}`);
                  }}
                >
                  变更
                </Button>
              </PermissionButton>
            ) : (
              ''
            )}
            {record.status === 'normal' && record.workflow_status !== 'needaudit' ? (
              <PermissionButton permission="close">
                <Button
                  type="link"
                  onClick={() => {
                    setShowCloseResone(true);
                    setCurrent(record.id);
                  }}
                >
                  关闭
                </Button>
              </PermissionButton>
            ) : (
              ''
            )}
            {['opening'].includes(record.status) && record.workflow_status !== 'needaudit' ? (
              <PermissionButton permission="formal_open">
                <Button
                  key="opening"
                  type="link"
                  size="small"
                  onClick={() => navigate(`${location.pathname}/change/${record.id}`, { state: { ...record } })}
                >
                  正式开办
                </Button>
              </PermissionButton>
            ) : (
              ''
            )}
          </Space>
        );
      },
    },
  ];
  const pageChange = (pageIndex, pageSize) => {
    set_stoge_pz(pageSize);
    search(form?.getFieldsValue(), pageSize, pageIndex);
  };
  React.useEffect(() => {
    search({}, pageSize, 1);
  }, []);

  return (
    <PageContainer
      header={
        <Breadcrumb
          items={[
            {
              title: location.pathname.indexOf('/sy') !== -1 ? '事业单位管理' : '行政单位管理',
            },
          ]}
        />
      }
    >
      <CloseReson
        show={showCloseResone}
        onCancel={(formPanelObject: FormPanelObject) => {
          formPanelObject.resetFields();
          setShowCloseResone(false);
        }}
        onOk={async (formPanelObject: FormPanelObject) => {
          const values = formPanelObject.getFieldsValue();
          const closeParams: CloseInstitution = {
            institution_id: current,
            ...values,
          };
          const res = await closeInstitution(closeParams);
          if (res.success) {
            message.success('关闭成功');
            setShowCloseResone(false);
            search(form?.getFieldsValue(), pageSize, pageIndex);
            form.resetFields();
          } else {
            formPanelObject.reVaildation(res);
          }
        }}
      />
      <Create
        show={showCreate}
        onCancel={() => setShowCreate(false)}
        onOk={() => {
          search(form?.getFieldsValue(), pageSize, pageIndex);
        }}
      />
      <FormPanel
        template={searchTemplate}
        key={1}
        btnsAlign={FormPanelBtnAlign.right}
        buttons={buildBtns()}
        submitBtnText="搜索"
        restBtnText="重置"
        onLoad={form => setForm(form)}
        onFinish={(formPanelObject: FormPanelObject) => {
          const params = formPanelObject.getFieldsValue();
          search(params, pageSize, 1);
          setForm(form);
          return false;
        }}
      />
      <Row style={{ marginTop: '10px' }}>
        <Col span={24}>
          <Space>
            {!Utils.getProps('isSchool') && (
              <>
                <PermissionButton permission="open">
                  <Button key="openkg" type="primary" onClick={() => setShowCreate(true)}>
                    开办
                  </Button>
                </PermissionButton>
                <PermissionButton permission="import">
                  <StandUploadExcel
                    uploadSrv="/school/v1/storage/school-upload-uri"
                    templateUrl={IMPORT_EXCEL_TEMPLATE.institution}
                    templateName="资源导入模版.xlsx"
                    showExcelSrv="/school/v1/storage/file-data-preview"
                    scene="institution"
                    onImport={async (data, file_name, bucket_name) => {
                      const res = await importInstitution({
                        file_name,
                        bucket_name,
                        scene: 'institution',
                      });
                      if (res.success) {
                        message.success('导入成功');
                        search({}, pageSize, 1);
                      } else {
                        message.error(res.message || res.details);
                      }
                      return res.success;

                    }}
                  >
                    导入
                  </StandUploadExcel>
                </PermissionButton>
              </>
            )}
          </Space>
        </Col>
      </Row>
      <Table
        className={styles.table}
        dataSource={dataSource}
        columns={columns}
        scroll={{ x: 'max-content' }}
        loading={tableLoading}
        pagination={{ ...PAGINATIONCONFIG, total, pageSize, current: pageIndex, onChange: pageChange }}
      />
    </PageContainer>
  );
};

export default Groups;
